<script lang='ts' setup>
import { api_send_login_code } from '@/apis/authentication/send_login_code.ts'
import { useMessage } from 'naive-ui'
import { reactive } from 'vue'
import { login } from '@/apis/authentication/login.ts'
import { pinia_global_state } from '@/state/state.ts'
import { useRouter } from 'vue-router'

const message = useMessage()
const router = useRouter()
const pinia = pinia_global_state()
const state = reactive<{ code: string, loading: boolean, send_loading: boolean }>({code: '', loading: false, send_loading: false})


async function send_login_code(): Promise<void> {
  state.send_loading = true
  await api_send_login_code()
  state.send_loading = false

  message.success('发送成功，邮件可能会有一定时间的延迟，请注意查收您的邮箱')
}

async function do_login_check(): Promise<void> {
  state.loading = true
  let response = await login(state.code)
  state.loading = false

  if (0 === response.code) {
    pinia.set_token(response.data.token)
    await router.push({name: 'dashboard'})
  }

  if (1 === response.code || 100201 == response.code) {
    message.error("口令错误")
  }
}
</script>

<template>
  <n-space align='center' class='login-wrap' justify='center'>
    <n-space :wrap-item='false' align='center' class='login-box' vertical>
      <n-space align='center' class='login-form' justify='center' vertical>
        <n-space :wrap-item='false' align='center' class='login-form-item'>
          <div style='flex-grow: 1'>
            <n-input-group>
              <n-input-group-label size='small'>口令</n-input-group-label>
              <n-input v-model:value='state.code' autofocus placeholder='请输入口令' size='small'></n-input>
              <n-button :loading='state.send_loading' size='small' type='primary' @click='send_login_code'>发送登录口令</n-button>
            </n-input-group>
          </div>
        </n-space>
        <n-space :wrap-item='false' align='center' class='login-form-item'>
          <div style='flex-grow: 1'>
            <n-button :loading='state.loading' size='small' style='width: 100%' type='primary' @click='do_login_check'>登录验证</n-button>
          </div>
        </n-space>
      </n-space>
    </n-space>
  </n-space>
</template>

<style scoped>
.login-wrap {
  height: calc(100vh - 1px);
}

.login-box {
  height: 600px;
  width: 800px;
  color: #FFFFFF;
  border-radius: 15px;
}

.login-form {
  flex-grow: 1;
}

.login-form-item {
  width: 450px;
}
</style>
